package com.haiyi.software.app.basic;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.haiyi.software.app.MainApplication;
import com.haiyi.software.app.R;
import com.haiyi.software.entity.UserInfo;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public abstract class ActivityBasicExchanger extends ActivityBasic {

	private final String TAG = "ActivityBasicExchanger";

	protected String str_server = null;

	private String str_requestName = "cgProduct.php";

	private Map<String, String> argsBody;

	private JsonObject jsonObj_return = null;

	@SuppressWarnings("unchecked")
	@Override
	public void requestNetworkData(Object... args) {

		argsBody = (Map<String, String>) args[0];

		str_server = this.getResources().getString(R.string.URL);

		String str_requestURL = str_server + str_requestName;

		AsyncHttpClient client = new AsyncHttpClient();

		RequestParams params = new RequestParams();

		params.add("args", getJsonArgs());

		client.post(str_requestURL, params, responseHandler);
	}

	private String getJsonArgs() {

		UserInfo myInfo = MainApplication.getInstance().getMineUserInfo();

		if (myInfo != null) {
			Map<String, Object> validator = new HashMap<String, Object>();

			validator.put("uid", myInfo.getUid());
			validator.put("uname", myInfo.getUname());
			validator.put("pwd", myInfo.getPwd());
			validator.put("uguid", myInfo.getUguid());

			argsBody.put("bz", "");
			argsBody.put("changeState", "1");

			Map<String, Object> ags = new HashMap<String, Object>();

			ags.put("validator", validator);
			ags.put("body", argsBody);

			Gson gson = new Gson();
			String s = gson.toJson(ags);

			Log.i("argsJson", s);

			return s;
		} else {
			return null;
		}
	}

	private AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {

			try {
				String str_jsonReturn = new String(responseBody, "UTF-8");

				JsonParser parser = new JsonParser();

				jsonObj_return = parser.parse(str_jsonReturn).getAsJsonObject();

				requestFinish(jsonObj_return);
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {
			// TODO 自动生成的方法存根
			requestFinish(jsonObj_return);
		}

	};
}
